# -*- coding: UTF-8 -*-
# file: oocrpc.py
# author: notedit
# date: 20110711
import re
import pymongo
import protocol as pro
from protocol import MGError

RE_FUNCCALL = re.compile(r'''^(?P<funcname>\w+)\((?P<args>.*?)\)$''')

remote_funcmapping = {}
def remote():
    global remote_funcmapping
    def inter1(func):
        funcname = func.__name__
        if not remote_funcmapping.has_key(funcname):
            remote_funcmapping[funcname] = func
        else:
            raise KeyError('%s:funcname declare more than once'%repr(funcname))
        def inter2(*args,**kwargs):
            return func(*args,**kwargs)
        return inter2
    return lambda func:inter1(func)

def query(querystring):
    matchobj = RE_FUNCCALL.search(querystring)
    if matchobj:
        gdict = matchobj.groupdict()
        funcname = gdict['funcname']
        func = remote_funcmapping.get(funcname)
        if func:
            ret = eval(querystring,{},remote_funcmapping)
            retdict = {'result':ret}
            return retdict
        else:
            raise MGError('FunctionNameError','%s does not exist'%repr(funcname))
    else:
        raise MGError('FunctionNameError',repr(querystring))

def start_console(port=27017):
    remote_funcmapping.update({'query':query})
    print str(remote_funcmapping)
    pro.start_console(remote_funcmapping,port)

def start_daemon(port=27017):
    remote_funcmapping.update({'query':query})
    pro.start_daemon(remote_funcmapping,port)
    
